package com.base.filter;


import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class TransactionFilter implements Filter {
	
	private WebApplicationContext webAppContext;

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest)request;
		String uri = req.getRequestURI();
		Transaction tx = null;
		Session session = null;
		//.do  --> transaction
		if(uri.contains(".do")){
			SessionFactory sessionFactory = (SessionFactory)webAppContext.getBean("sessionFactory");
			session = sessionFactory.getCurrentSession();
			tx = session.beginTransaction();
		}
		try{
			chain.doFilter(request, response);
			//commit
			if(tx != null){
				tx.commit();
			}
		}catch(Exception e){
			//rollback
			if(tx != null){
				tx.rollback();
			}
			e.printStackTrace();
		}finally{
			if(session != null && session.isOpen()){
				session.close();
			}
		}
		
	}

	
	public void init(FilterConfig config) throws ServletException {
		webAppContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
	}
	public void destroy() {

	}


}
